from django.shortcuts import render, redirect, HttpResponse
from medical import models
from medical.utils.pagination import Pagination
from medical.utils.bootstrap import BootStrapModelForm
from django.core.exceptions import ValidationError
from django import forms

class UsersaddModelForm(BootStrapModelForm):
    confirm_pwd = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True),
    )

    class Meta:
        model = models.users
        fields = ["user_id", "user_name", "user_pwd", "confirm_pwd", "user_real_name", "user_email", "user_tel"]

    def clean_user_tel(self):
        txt_tel = self.cleaned_data["user_tel"]
        # 验证手机号存在
        print(self.instance.pk)
        exists = models.users.objects.exclude(user_id=self.instance.pk).filter(user_tel=txt_tel).exists()
        if exists:
            raise ValidationError("手机号已经存在")
        # return txt_mobile

        elif len(txt_tel) != 11:
            # 验证不通过
            raise ValidationError("手机号码格式错误")
        # 验证通过，用户输入的值返回
        else:
            return txt_tel

    def clean_user_email(self):
        txt_email = self.cleaned_data["user_email"]
        # 验证手机号存在
        print(self.instance.pk)
        exists = models.users.objects.exclude(user_id=self.instance.pk).filter(user_email=txt_email).exists()
        if exists:
            raise ValidationError("Email已经存在")
        # return txt_email
        else:
            return txt_email

    def clean_confirm_pwd(self):
        pwd = self.cleaned_data.get("user_pwd")
        confirm = self.cleaned_data.get("confirm_pwd")
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，此字段以后保存到数据库就是什么。
        return confirm


class UserseditModelForm(BootStrapModelForm):
    class Meta:
        model = models.users
        fields = ["user_name", "user_pwd", "user_real_name", "user_email", "user_tel"]

    def clean_user_tel(self):
        txt_tel = self.cleaned_data["user_tel"]
        # 验证手机号存在
        print(self.instance.pk)
        exists = models.users.objects.exclude(user_id=self.instance.pk).filter(user_tel=txt_tel).exists()
        if exists:
            raise ValidationError("手机号已经存在")
        # return txt_mobile

        elif len(txt_tel) != 11:
            # 验证不通过
            raise ValidationError("手机号码格式错误")
        # 验证通过，用户输入的值返回
        else:
            return txt_tel

    def clean_user_email(self):
        txt_email = self.cleaned_data["user_email"]
        # 验证手机号存在
        print(self.instance.pk)
        exists = models.users.objects.exclude(user_id=self.instance.pk).filter(user_email=txt_email).exists()
        if exists:
            raise ValidationError("Email已经存在")
        # return txt_email
        else:
            return txt_email


def users_list(request):
    # 1.根据自己的情况去筛选自己的数据
    queryset = models.users.objects.all()

    # 2.实例化分页对象
    page_object = Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 生成页码
    }

    return render(request, 'users_list.html', context)


def users_add(request):
    title = "添加用户"
    if request.method == "GET":
        form = UsersaddModelForm()
        return render(request, 'template.html', {'form': form, "title": title})

    form = UsersaddModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/users/list/')

    return render(request, 'template.html', {'form': form, 'title': title})


def users_edit(request, nid):
    title = "修改用户"

    row_object = models.users.objects.filter(user_id=nid).first()
    if not row_object:
        return redirect('/users/list/')
    #
    title = "编辑管理员"
    if request.method == "GET":
        form = UserseditModelForm(instance=row_object)
        return render(request, 'template.html', {"form": form, "title": title})

    form = UserseditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/users/list/')
    return render(request, 'template.html', {"form": form, "title": title})


def users_delete(request, nid):
    models.users.objects.filter(user_id=nid).delete()
    return redirect('/users/list')
